<template>
  <div>
    <h1>Computed属性示例</h1>
    <p>原始数据:{{ message }}</p>
    <p>反转后的数据:{{ reversedMessage }}</p>
    <p>数据长度:{{ messageLength }}</p>
    <input v-model="inputText1" type="text" />
    <p>输入内容的大写:{{ uppercaseInput }}</p>
    <hr />
    <h1>Watch 监听示例</h1>
    <p>计数器:{{ counter }}</p>
    <button @click="addFn">增加</button>
    <p>输入的内容为:{{ inputText2 }}</p>
    <input v-model="inputText2" type="text" />
    <p v-show="isInputEmpty">输入框为空</p>
    <hr />
    <div>
      <h1>v-model绑定表单</h1>
      <h3>文本框</h3>
      <textarea cols="30" rows="10" v-model.lazy="intro"></textarea>
      <p>文本输入框的值:{{ intro }}</p>
      <hr />
      <h3>checkbox单选框</h3>
      <label for="agreee"> <input id="agree" type="checkbox" v-model="isAgree" />同意协议 </label>
      <p>单选框的值:{{ isAgree }}</p>
      <hr />
      <h3>checkbox多选框</h3>
      <p>爱好：{{ hobbies }}</p>
      <label for="basketball"> <input id="basketball" type="checkbox" v-model="hobbies" value="篮球" />篮球 </label>
      <label for="football"> <input id="football" type="checkbox" v-model="hobbies" value="足球" />足球 </label>
      <label for="tennis"> <input id="tennis" type="checkbox" v-model="hobbies" value="网球" />网球 </label>
      <label for="ping-pang"> <input id="ping-pang" type="checkbox" v-model="hobbies" value="乒乓球" />乒乓球 </label>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello Wrold!',
      inputText1: '',
      inputText2: '',
      counter: 0,
      intro: '',
      isAgree: false,
      hobbies: []
    }
  },
  computed: {
    reversedMessage() {
      console.log(this.message.split(''))
      return this.message.split('').reverse().join('')
    },
    messageLength() {
      return this.message.length
    },
    uppercaseInput() {
      return this.inputText1.toUpperCase()
    },
    formattedHobbies() {
      // 将数组转换为用逗号分隔的字符串
      return this.hobbies.join(', ')
    }
  },
  watch: {
    counter(newValue, oldValue) {
      console.log(`${oldValue}变为${newValue}`)
      if (newValue >= 5) {
        alert('计数器已经达到5了')
      }
    },
    inputText2(newValue) {
      if (newValue.trim() === '') {
        this.isInputEmpty = true
      } else {
        this.isInputEmpty = false
      }
    }
  },
  methods: {
    addFn() {
      this.counter++
    }
  }
}
</script>

<style lang="scss" scoped></style>
